package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

type Refunds struct {
	Id                  int64
	DepartmentId        int64
	Archives            *Archives `orm:"rel(fk);null;on_delete(set_null)"`
	ManualNumber        string
	RetailsId           int64 //销售单据ID
	RetailsManualNumber string
	BusinessName        string
	RetailsTime         int64   //销售时间
	TotalMoney          float64 //销售实付金额
	SumPayable          float64 //实退金额
	AlipayMoney         float64 //支付宝
	WechatMoney         float64 //微信支付
	CashMoney           float64 //现金
	Remarks             string
	CreatedAt           int64
	UpdatedAt           int64
	CreatedBy           string
	UpdatedBy           string
	RefundsData         []*RefundsData `orm:"reverse(many);null"`
}

type RefundsQueryParam struct {
	BaseQueryParam
	ManualNumber   string //单号
	ArchivesName   string //客户名
	ArchivesMobile string //客户手机
	StartDate      string //开始日期
	EndDate        string //结束日期
	CreatedBy      string //操作人
	Depid          int64
	Business       string //营业员
}

func (a *Refunds) TableName() string {
	return RefundsTableName()
}

func RefundsTableName() string {
	return TableName("sa_refunds")
}

//查询分页数据
func RefundsPageList(params *RefundsQueryParam) ([]*Refunds, int64) {
	query := orm.NewOrm().QueryTable(RefundsTableName()).RelatedSel("Archives")
	data := make([]*Refunds, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	if len(params.ArchivesName) > 0 {
		query = query.Filter("Archives__Realname", params.ArchivesName)
	}
	if len(params.ArchivesMobile) > 0 {
		query = query.Filter("Archives__Mobile", params.ArchivesMobile)
	}
	if len(params.Business) > 0 {
		query = query.Filter("business_name", params.Business)
	}

	if len(params.StartDate) > 0 {
		query = query.Filter("created_at__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("created_at__lte", utils.GetDateParse(params.EndDate)+86400)
	}

	if len(params.CreatedBy) > 0 {
		query = query.Filter("CreatedBy", params.CreatedBy)
	}

	query = query.Filter("department_id", params.Depid)
	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}

func queryRefundsTimeSoltSeter(starttime, endtime int64, relatesel ...interface{}) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(RefundsTableName())
	if len(relatesel) > 0 {
		query = query.RelatedSel(relatesel...)
	}
	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	query = query.SetCond(cond)

	return query
}

//按时间段获取销售数据
func QueryRefundsTimeSoltSeter(curuser BackendUser, starttime, endtime int64, relatesel ...interface{}) []*Refunds {

	data := make([]*Refunds, 0)
	queryRefundsTimeSoltSeter(starttime, endtime, relatesel...).Filter("department_id", curuser.DepartmentId).Limit(-1).OrderBy("-id").All(&data)

	return data
}

//修改销售信息
func (a *Retails) RefundsEdit(fileds ...string) error {

	if _, err := orm.NewOrm().Update(a, fileds...); err != nil {
		return err
	}

	return nil
}

//按时间段获取零售count
func QueryRefundsTimeSoltSeterCount(starttime, endtime int64) int64 {

	count, _ := queryRetailsTimeSoltSeter(starttime, endtime).Count()

	return count
}

//获取一个单据所有信息
func QueryRefundsDetails(id int64) (*Refunds, error) {

	retail := new(Refunds)
	retail.Id = id
	if err := orm.NewOrm().Read(retail); err != nil {
		return nil, err
	}
	//获取data数据
	retailData := make([]*RefundsData, 0)
	if _, err := orm.NewOrm().QueryTable(RefundsDataTableName()).RelatedSel("Products").Filter("retails_id", retail.Id).All(&retailData); err != nil {
		return nil, err
	}
	retail.RefundsData = retailData

	//获取档案数据
	archive := new(Archives)
	archive.Id = retail.Archives.Id
	if err := orm.NewOrm().Read(archive); err == nil {
		retail.Archives = archive
	}

	return retail, nil
}

func CreateRefundsDocumentNumber(c *BackendUser) string {
	var documentNumber string = ""
	stat := utils.GetDateParse(time.Now().Format("2006-01-02"))
	end := stat + 86400
	documentNumber = fmt.Sprintf("%s%06d", time.Now().Format("20060102150405"), QueryRefundsTimeSoltSeterCount(stat, end)+1)
	return documentNumber
}
